import request from './request.js';
import base64 from 'base-64';
import axios from "axios";
import {getDB} from "./Utils.js";
import dayjs from "dayjs";
import logger from "log4js";

const BLZ_URL = 'https://us.api.blizzard.com/hearthstone/cards';

const BLZ_HS_CARD_BACKS_URL = "https://us.api.blizzard.com/hearthstone/cardbacks"

export const getAllClasses = () => {
    return request({url: '/hs/classes', method: 'GET'});
}

export const getCards = (query) => {
    return request({url: `${BLZ_URL}`, method: 'GET', params: query});
}

export const getToken = () => {
    return request({url: '/token', method: 'GET'});
}

export const getCardBacks = (param) => {
    return request({url: `${BLZ_HS_CARD_BACKS_URL}`, method: 'GET', params: param});
}

export const getCardBackDetails = (idOrSlug) => {
    return request({url: `${BLZ_HS_CARD_BACKS_URL}/${idOrSlug}`, method: 'GET'});
}

export const getHsToken = async () => {
    const db = await getDB()
    // 获取token
    const credentials = `${process.env.BATTLENET_HS_CLIENT_ID}:${process.env.BATTLENET_CLIENT_SECRET}`;
    const basicAuth = `Basic ${base64.encode(credentials)}`
    const reqConfig = {
        method: 'POST', url: `${process.env.BATTLENET_HS_BASIC_OAUTH_URL}`, headers: {
            Authorization: `Bearer ${basicAuth}`, 'Content-Type': 'application/x-www-form-urlencoded',
        }, auth: {
            username: process.env.BATTLENET_HS_CLIENT_ID, password: process.env.BATTLENET_HS_SECRET,
        }, data: {
            'grant_type': 'client_credentials',
        }
    }
    try {
        const ret = await axios(reqConfig)
        if (ret.status === 200) {
            db.data.blzHsToken = ret.data.access_token
            db.data.expiresIn = dayjs().add(ret.data.expires_in, 's').format('YYYY-MM-DD HH:mm:ss')
            await db.write()
        } else {
            logger.getLogger(`hsapi.js - getHsToken`).error(`获取token失败 ${ret.status}`)
        }
    } catch (e) {
        logger.getLogger(`hsapi.js - getHsToken`).error(`获取token失败 ${e}`)
    }

}